package com.gcxy.core.aop;

import cn.hutool.core.bean.BeanUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;

@Aspect
@Component
public class AgencyIdAspect {

    @Pointcut("execution(* com.gcxy.controller..*(..))")
    public void controllerMethods() {}

    @Around("controllerMethods()")
    public Object aroundControllerMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        // 获取 HttpServletRequest
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();

        Object agencyIdFromAttr = request.getAttribute("agencyId");
        Integer agencyId = null;
        if (agencyIdFromAttr != null) {
            // 尝试从 request 的 attributes 中获取 agencyId
            agencyId = Integer.parseInt(agencyIdFromAttr.toString());
        }
        // 遍历参数
        for (int i = 0; i < args.length; i++) {
            if (BeanUtil.isMatchName(args[i].getClass(), "agencyId",true) && agencyId != null) {
                args[i] = agencyId;
            } else if (BeanUtil.getPropertyDescriptor(args[i].getClass(), "agencyId") != null && agencyId != null) {
                BeanUtil.setProperty(args[i], "agencyId", agencyId);
            }
        }
        // 继续执行原方法
        return joinPoint.proceed(args);
    }
}